package com.sq.imp.MyMenuManagers;

import com.sq.abstractClass.Text;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.ArrayList;

public class FileManager {
    private final Text textArea;
    private final JFrame frame;
    private FileChannel fileChannel;
    private FileLock fileLock;

    public FileManager(Text textArea, JFrame frame) {
        this.textArea = textArea;
        this.frame = frame;
    }

    public void newFile() {
        if (fileLock != null) {
            try {
                fileLock.release(); // 解锁文件
                fileLock = null;
                fileChannel.close();
                fileChannel = null;
                textArea.setText(""); // 清空文本区域
                JOptionPane.showMessageDialog(frame, "文件已解锁，可以创建新文件！", "提示", JOptionPane.INFORMATION_MESSAGE);
            } catch (IOException e) {
                JOptionPane.showMessageDialog(frame, "解锁文件失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            textArea.setText(""); // 清空文本区域
        }
        textArea.setFile(null);
        textArea.setEncoding("");
    }

    public void openFile() {

        ArrayList<File> file = new ArrayList<>();
        ArrayList<String> encoding = new ArrayList<>();
        selectFileAndEncoding(textArea, file, encoding);
        if (file.isEmpty() || encoding.isEmpty()) {
            System.out.println("文件未选择成功或编码未选择成功");
            return;
        }
        try (RandomAccessFile raf = new RandomAccessFile(file.get(0), "rw")) {
            FileInputStream fis = new FileInputStream(file.get(0));
            InputStreamReader isr = new InputStreamReader(fis, encoding.get(0));
            BufferedReader bufferedReader = new BufferedReader(isr);
            // 读取文件内容到 JTextArea
            textArea.read(bufferedReader, null);
            bufferedReader.close(); // 关闭流
            textArea.setFile(file.get(0));
            textArea.setEncoding(encoding.get(0));
            fileChannel = raf.getChannel();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(frame, "打开文件失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void saveFile() {
        if (textArea.getFile() == null || textArea.getEncoding() == null) {
            ArrayList<File> file = new ArrayList<>();
            ArrayList<String> encoding = new ArrayList<>();
            selectFileAndEncoding(textArea, file, encoding);
            if (file.isEmpty() || encoding.isEmpty() || file.get(0) == null || encoding.get(0) == null) {
                System.out.println("文件未选择成功或编码未选择成功");
                return;
            }else {
                textArea.setFile(file.get(0));
                textArea.setEncoding(encoding.get(0));
            }
        }
        saveFile(textArea.getFile(), textArea.getEncoding());
    }

    public void saveFile(File file, String encoding) {

        try {
            FileOutputStream fos = new FileOutputStream(file);
            OutputStreamWriter osr = new OutputStreamWriter(fos, encoding);
            BufferedWriter bw = new BufferedWriter(osr);
            textArea.write(bw);
            bw.close();
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(frame, "文件未找到！", "错误", JOptionPane.ERROR_MESSAGE);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(frame, "读取文件时发生错误！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void saveFileAs() {
        ArrayList<File> file = new ArrayList<>();
        ArrayList<String> encoding = new ArrayList<>();
        selectFileAndEncoding(textArea, file, encoding);
        if (file.isEmpty() || encoding.isEmpty()) {
            System.out.println("文件未选择成功或编码未选择成功");
            return;
        } else if(file.get(0).exists()) {
            if (1 == JOptionPane.showConfirmDialog(frame, "文件已存在，是否覆盖",
                    "提示", JOptionPane.YES_NO_OPTION))
                return;
        }
        saveFile(file.get(0), encoding.get(0));

    }

    public static void selectFileAndEncoding(Component parent, ArrayList<File> file, ArrayList<String> encoding) {
        if (!file.isEmpty() || !encoding.isEmpty()) {
            System.out.println("file and encoding must be empty");
            return;
        }

        JFileChooser fileChooser = new JFileChooser();
        int result = fileChooser.showOpenDialog(parent);
        if (result == JFileChooser.APPROVE_OPTION) {
            file.add(fileChooser.getSelectedFile());

            String[] encodingOptions = {"UTF-8", "GBK", "ISO-8859-1", "UTF-16", "Windows-1252", "Other"};
            String selectedEncoding = (String) JOptionPane.showInputDialog(
                    parent,
                    "Select the file encoding:",
                    "Encoding Selection",
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    encodingOptions,
                    encodingOptions[0]);

            if (selectedEncoding != null) {
                if ("Other".equals(selectedEncoding)) {
                    selectedEncoding = JOptionPane.showInputDialog(parent, "Enter custom encoding:");
                    if (selectedEncoding == null || selectedEncoding.trim().isEmpty()) {
                        System.out.println("No custom encoding provided");
                    }
                }
                if (selectedEncoding != null) {
                    encoding.add(selectedEncoding);
                }
            } else {
                System.out.println("No encoding selected");
            }
        } else {
            System.out.println("No file selected");
        }
    }






}